package com.jixiang.user.config;

import cn.hutool.core.util.StrUtil;
import com.jixiang.model.user.entity.UsUser;
import com.jixiang.utils.thread.UserThread;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class UserInterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String userId = request.getHeader("userId");
        if(StrUtil.isNotBlank(userId)){
            UsUser user = new UsUser();
            user.setId(Long.valueOf(userId));
            UserThread.setUser(user);
        }
        return HandlerInterceptor.super.preHandle(request, response, handler);
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        UserThread.clearUser();
        HandlerInterceptor.super.afterCompletion(request, response, handler, ex);
    }
}
